//
//  NetWorkTools.m
//  swift-01
//
//  Created by China Dragon on 2023/8/18.
//

#import "NetWorkTools.h"
@interface NetWorkTools()
@property(nonatomic, copy) void(^finishedBlock )(NSString *);

@end
/*
 block 循环引用
 
 如果不能直接调用，定义一个属性记录 block ，在需要的时候执行
 */
@implementation NetWorkTools
-(void)loadData{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSLog(@"异步处理1");
        
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"准备处理1");
        });
    });
}

//直接调用
- (void)loadData2:(void (^)(NSString * _Nonnull))finished{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSLog(@"异步处理2");
        dispatch_sync(dispatch_get_main_queue(), ^{
            NSLog(@"准备处理2");
            finished(@"响应成功数据");
        });
    });
}

//间接调用 会出现循环引用
- (void)loadData3:(void (^)(NSString * _Nonnull))finished{
    
    //使用属性记录 block
    self.finishedBlock = finished;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSLog(@"异步处理3");
        
        //模拟延时
        [NSThread sleepForTimeInterval:2.0];
        
        dispatch_sync(dispatch_get_main_queue(), ^{
            NSLog(@"准备处理3");
//            finished(@"响应成功数据");
            // 由working调用finished
            [self working]; //这里会出现循环引用
        });
    });
}

-(void) working{
    //执行回调函数
    if(self.finishedBlock != nil){
        self.finishedBlock(@"hello ....");
    }
}

- (void)dealloc{
    NSLog(@"NetWorkTools 控制器 结束");
}

@end
